<template>
    <div class="user-manage">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>用户管理</span>
            <el-button type="primary" @click="handleAdd">新增用户</el-button>
          </div>
        </template>
  
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-form :inline="true" :model="searchForm">
            <el-form-item label="用户名">
              <el-input v-model="searchForm.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="部门">
              <el-select v-model="searchForm.department" placeholder="请选择部门">
                <el-option label="技术部" value="技术部" />
                <el-option label="人事部" value="人事部" />
                <el-option label="财务部" value="财务部" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态">
                <el-option label="正常" value="normal" />
                <el-option label="禁用" value="disabled" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
  
        <!-- 用户列表 -->
        <el-table :data="userList" border style="width: 100%">
          <el-table-column prop="id" label="工号" width="100" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="role" label="角色" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.role === 'admin' ? 'danger' : ''">
                {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'normal' ? 'success' : 'info'">
                {{ scope.row.status === 'normal' ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                @click="handleEdit(scope.row)"
                class="action-btn"
              >
                编辑
              </el-button>
              <el-button 
                link 
                type="primary" 
                @click="handleResetPassword(scope.row)"
                class="action-btn"
              >
                重置密码
              </el-button>
              <el-button 
                link 
                :type="scope.row.status === 'normal' ? 'danger' : 'primary'"
                @click="handleToggleStatus(scope.row)"
                class="action-btn"
              >
                {{ scope.row.status === 'normal' ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 用户表单对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="工号" prop="id">
            <el-input v-model="form.id" :disabled="dialogType === 'edit'" />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" :disabled="dialogType === 'edit'" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
            <el-input v-model="form.password" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogType === 'add'">
            <el-input v-model="form.confirmPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-select v-model="form.department" placeholder="请选择部门">
              <el-option label="技术部" value="技术部" />
              <el-option label="人事部" value="人事部" />
              <el-option label="财务部" value="财务部" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" placeholder="请选择角色">
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  // 搜索表单
  const searchForm = reactive({
    username: '',
    department: '',
    status: ''
  })
  
  // 用户列表数据
  const userList = ref([
    {
      id: 'EMP001',
      username: 'zhangsan',
      name: '张三',
      department: '技术部',
      role: 'admin',
      status: 'normal',
      createTime: '2024-03-01 10:00:00',
      phone: '13800138000',
      email: 'zhangsan@example.com'
    },
    {
      id: 'EMP002',
      username: 'lisi',
      name: '李四',
      department: '人事部',
      role: 'user',
      status: 'normal',
      createTime: '2024-03-02 11:00:00',
      phone: '13800138001',
      email: 'lisi@example.com'
    }
  ])
  
  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(100)
  
  // 对话框相关
  const dialogVisible = ref(false)
  const dialogType = ref('add')
  const formRef = ref(null)
  const form = reactive({
    id: '',
    username: '',
    name: '',
    password: '',
    confirmPassword: '',
    department: '',
    role: '',
    phone: '',
    email: ''
  })
  
  // 表单验证规则
  const validatePass = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请输入密码'))
    } else {
      if (form.confirmPassword !== '') {
        formRef.value.validateField('confirmPassword')
      }
      callback()
    }
  }
  
  const validatePass2 = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请再次输入密码'))
    } else if (value !== form.password) {
      callback(new Error('两次输入密码不一致!'))
    } else {
      callback()
    }
  }
  
  const rules = {
    id: [
      { required: true, message: '请输入工号', trigger: 'blur' },
      { pattern: /^EMP\d{3,}$/, message: '工号格式为EMP开头加3位以上数字', trigger: 'blur' }
    ],
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    password: [
      { validator: validatePass, trigger: 'blur' }
    ],
    confirmPassword: [
      { validator: validatePass2, trigger: 'blur' }
    ],
    department: [
      { required: true, message: '请选择部门', trigger: 'change' }
    ],
    role: [
      { required: true, message: '请选择角色', trigger: 'change' }
    ],
    phone: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
  }
  
  // 搜索处理
  const handleSearch = () => {
    console.log('搜索条件：', searchForm)
  }
  
  // 重置搜索
  const resetSearch = () => {
    searchForm.username = ''
    searchForm.department = ''
    searchForm.status = ''
  }
  
  // 新增用户
  const handleAdd = () => {
    dialogType.value = 'add'
    Object.keys(form).forEach(key => {
      form[key] = ''
    })
    dialogVisible.value = true
  }
  
  // 编辑用户
  const handleEdit = (row) => {
    dialogType.value = 'edit'
    Object.keys(form).forEach(key => {
      if (key !== 'password' && key !== 'confirmPassword') {
        form[key] = row[key]
      }
    })
    dialogVisible.value = true
  }
  
  // 重置密码
  const handleResetPassword = (row) => {
    ElMessageBox.confirm(
      `确认重置用户"${row.name}"的密码吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButton:'取消',
        type:'warning'
      }
    ).then(()=>{
      ElMessage.success('密码重置成功')
    }).catch(()=>{
      ElMessage.info('已取消重置')
    })
  }

  // 提交表单
  const submitForm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          // 新增用户
          userList.value.push({
            id: form.id,
            username: form.username,
            name: form.name,
            department: form.department,
            role: form.role,
            status: 'normal',
            createTime: new Date().toLocaleString(),
            phone: form.phone,
            email: form.email
          })
          ElMessage.success('新增用户成功')
          dialogVisible.value = false
        } else {
          // 编辑用户
          const index = userList.value.findIndex(item => item.id === form.id)
          if (index !== -1) {
            userList.value[index] = {
              ...userList.value[index],
              ...form
            }
            ElMessage.success('编辑用户成功')
            dialogVisible.value = false     
          } else {
            ElMessage.error('用户不存在')
          }
        }
      } else {
        ElMessage.error('请检查输入内容')
      } 
    })
  }

  // 取消表单
  const cancelForm = () => {
    dialogVisible.value = false
  }

  // 切换状态
  const handleToggleStatus = (row) => {
    const newStatus = row.status === 'normal' ? 'disabled' : 'normal'
    userList.value[index] = {
      ...userList.value[index],
      status: newStatus
    }
    ElMessage.success(`用户状态已切换为${newStatus === 'normal' ? '正常' : '禁用'}`)
  }

  // 分页处理
  const handleSizeChange = (val) => {
    pageSize.value = val
    // 重新加载数据
  }

  const handleCurrentChange = (val) => {
    currentPage.value = val
    // 重新加载数据
  }

</script>

<style scoped lang="scss">
.user-manage {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-area {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  :deep(.el-dialog) {
    .el-form {
      max-height: 60vh;
      overflow-y: auto;
      padding-right: 20px;
      
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-thumb {
        background-color: #dcdfe6;
        border-radius: 3px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .action-btn {
    font-size: 13px;
    font-weight: 500;
    transition: all 0.3s;
    margin-right: 10px;
    
    &:hover {
      transform: translateY(-2px);
      opacity: 0.8;
    }
    
    &:active {
      color: #096dd9;
    }
    
    &.el-button--danger:hover {
      opacity: 0.8;
      transform: translateY(-2px);
    }
    
    &.el-button--danger:active {
      color: #cf1322;
    }
  }
}
</style>

